// pages/user-tasks/user-tasks.js
const app = getApp()

Page({
  data: {
    tasks: [],
    loading: true,
    refreshing: false,
    activeTasks: 0,
    completedTasks: 0,
    totalQuantity: 0
  },

  onLoad() {
    this.loadTasks()
  },

  onShow() {
    this.loadTasks()
  },

  onPullDownRefresh() {
    this.setData({
      refreshing: true
    })
    this.loadTasks().then(() => {
      wx.stopPullDownRefresh()
      this.setData({
        refreshing: false
      })
    })
  },

  // 加载任务列表
  loadTasks() {
    return app.userRequest({
      url: '/getTasks'
    }).then((res) => {
      const tasks = res.data || []
      
      // 计算统计数据
      let activeTasks = 0
      let completedTasks = 0
      let totalQuantity = 0
      
      tasks.forEach(task => {
        // 修复状态判断逻辑：只有当已报数量 >= 分配数量时，任务才算完成
        if (task.reported_quantity >= task.quantity && task.quantity > 0) {
          completedTasks++
        } else {
          activeTasks++
        }
        totalQuantity += task.quantity || 0
        
        // 计算进度百分比
        if (task.quantity && task.quantity > 0) {
          task.progress_percent = Math.round((task.reported_quantity / task.quantity) * 100)
        } else {
          task.progress_percent = 0
        }
        
        // 添加正确的状态标识
        task.isCompleted = (task.reported_quantity >= task.quantity && task.quantity > 0)
        task.isStarted = (task.reported_quantity > 0)
        task.isPending = (task.reported_quantity === 0)
      })
      
      this.setData({
        tasks: tasks,
        activeTasks: activeTasks,
        completedTasks: completedTasks,
        totalQuantity: totalQuantity,
        loading: false
      })
    }).catch((err) => {
      console.error('获取任务列表失败:', err)
      this.setData({
        loading: false
      })
      wx.showToast({
        title: '获取任务失败',
        icon: 'none'
      })
    })
  },

  // 跳转到报工页面
  goToReport(e) {
    const taskId = e.currentTarget.dataset.id
    wx.navigateTo({
      url: `/pages/user-report/user-report?allocation_id=${taskId}`
    })
  },

  // 刷新任务列表
  refreshTasks() {
    this.loadTasks()
  }
}) 